package com.glory.dgcpcpda.base;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.activity.LoginActivity;
import com.glory.dgcpcpda.activity.SettingActivity;
import com.glory.dgcpcpda.adapter.AddCarrierDataAdapter;
import com.glory.dgcpcpda.utils.EditTextEnterUtils;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.base.FreeUI_BaseActivity;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_DownloadFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_VersionEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_NetUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Optional;

/**
 * FileName: BaseActivity
 * Author: XJH
 * Date: 2020/5/12 16:21
 * Description:
 * History:
 */
public abstract class BaseActivity extends FreeUI_BaseActivity {

    private LinearLayout llMain;
    private static List<Activity> mActivityList = new ArrayList<>();
    private int code;

    public interface editTextListener{
        void onTextChangeListener(String s);
    }

    public interface onSubmitListener{
        void setOnSubmitListener();
    }

    @Override
    protected abstract int getLayoutResId();

    @Override
    protected abstract void initView();

    @Override
    protected abstract void initData();

    protected void setMainLayout(LinearLayout llMain){
        this.llMain = llMain;
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle(Constant.CURRENT_USER + "--" + Constant.CURRENT_DESC);
        return new FreeUI_AddViewEntity("header", llMain);
    }

    protected AddCarrierDataAdapter getCarrierAdapter(){
        AddCarrierDataAdapter addCarrierDataAdapter = new AddCarrierDataAdapter(null,getSupportFragmentManager());
        addCarrierDataAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        addCarrierDataAdapter.isFirstOnly(true);
        return addCarrierDataAdapter;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        detectionUpdate();
    }

    private void detectionUpdate()    {
        PackageManager manager = getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = info.versionName;
        FreeUI_EntityCallBack<FreeUI_VersionEntity> callBack = new FreeUI_EntityCallBack<FreeUI_VersionEntity>
                (new TypeToken<FreeUI_VersionEntity>() {
                }.getType()) {

            @Override
            public void onSuccess(Response<FreeUI_VersionEntity> response) {
                FreeUI_VersionEntity entity = response.body();
                entity.setCurrentVersion(version);
                code = compareVersion(version,entity.getVersion());
                Toast.makeText(BaseActivity.this, version+"/"+entity.getVersion(), Toast.LENGTH_SHORT).show();
                if(code == -1 ||code == 1) {
                    FreeUI_DownloadFragmentDialog downloadFragmentDialog = new FreeUI_DownloadFragmentDialog();
                    downloadFragmentDialog.setData(entity);
                    downloadFragmentDialog.show(getSupportFragmentManager(),"DOWNLOAD");
                }

            }

            @Override
            public void onError
                    (Response<FreeUI_VersionEntity> response) {
                super.onError(response);
            }
        };
        Map<String, String> map = new HashMap<>();
        FreeApi_NetUtils.requestGetNet(Constant.FILE_URL, this, map, callBack);
    }


    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        } else {
            String[] version1Array = version1.split("\\.");
            String[] version2Array = version2.split("\\.");
            Log.d("HomePageActivity", "version1Array==" + version1Array.length);
            Log.d("HomePageActivity", "version2Array==" + version2Array.length);
            int index = 0;
            int minLen = Math.min(version1Array.length, version2Array.length);
            int diff = 0;
            Log.d("HomePageActivity", "verTag2=2222=" + version1Array[index]);

            while(index < minLen && (diff = Integer.parseInt(version1Array[index]) - Integer.parseInt(version2Array[index])) == 0) {
                ++index;
            }

            if (diff == 0) {
                int i;
                for(i = index; i < version1Array.length; ++i) {
                    if (Integer.parseInt(version1Array[i]) > 0) {
                        return 1;
                    }
                }

                for(i = index; i < version2Array.length; ++i) {
                    if (Integer.parseInt(version2Array[i]) > 0) {
                        return -1;
                    }
                }

                return 0;
            } else {
                return diff > 0 ? 1 : -1;
            }
        }
    }


    /**
     * 不获取焦点初始化editText
     * @param editText
     * @param listener
     * @param
     */
    protected void initEdit(EditText editText, final editTextListener listener){
        EditTextEnterUtils.initEnterToUpperCase(editText);
        FreeApi_EditTextUtils.setEditTextListener(editText, this, s -> {
            if (listener != null){
                listener.onTextChangeListener(s);
            }
        });
    }


    /**
     * 不获取焦点初始化editText
     * @param editText
     * @param listener
     * @param
     */
    protected void initEdit2(EditText editText, final editTextListener listener){
        editText.setImeOptions(EditorInfo.IME_ACTION_GO);
        editText.setSingleLine(true);
        editText.setOnEditorActionListener((textView, i, keyEvent) -> {
            if (EditorInfo.IME_ACTION_GO == i) {
                String text = editText.getText().toString();
                //转大写并触发扫描效果
                editText.getText().clear();
                editText.setText(text);
                editText.setSelection(editText.getText().length());
                return true;
            }
            return false;
        });
        FreeApi_EditTextUtils.setEditTextListener(editText, this, s -> {
            if (listener != null){
                listener.onTextChangeListener(s);
            }
        });
    }

    protected void addActivity(Activity activity){
        mActivityList.add(activity);
    }

    protected void removeActivity(Activity activity){
        mActivityList.remove(activity);
    }

    protected void removeAllActivity(){
        mActivityList.clear();
    }

    protected void addAllActivity(List<Activity> list){
        mActivityList.addAll(list);
    }

    protected void finishAllActivity(){
        for (Activity data : mActivityList){
            data.finish();
        }
    }

    protected void showConfirmDialogFinishAll(String message){
        FreeApi_DialogUtils.getConfirmDialog(this, "确定", message, () -> {
            finishAllActivity();
        }).show(getSupportFragmentManager(),"CONFIRM_DIALOG");
    }

    protected void showConfirmDialog(final Activity context, String message){
        FreeApi_DialogUtils.getConfirmDialog(this, "确定", message, () -> context.finish()).show(getSupportFragmentManager(),"CONFIRM_DIALOG");
    }

    protected void showConfirmDialog(String message){
        FreeApi_DialogUtils.getConfirmDialog(this, "确定", message, () -> {
        }).show(getSupportFragmentManager(),"CONFIRM_DIALOG");
    }

    protected void initRecyclerView(RecyclerView recyclerView, Context context){
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerItemDecoration(context, 1));
    }

    public void showSubmitDialog(onSubmitListener listener){
        FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "确定要提交?", () -> {
            //确定
            if (listener != null){
                listener.setOnSubmitListener();
            }
        }, () -> {
        }).show(getSupportFragmentManager(),"SUBMIT_DIALOG");
    }

    public void showSubmitDialog(onSubmitListener listener,String message){
        FreeApi_DialogUtils.getConfirmAndCancelDialog(this, message, () -> {
            //确定
            if (listener != null){
                listener.setOnSubmitListener();
            }
        }, () -> {
        }).show(getSupportFragmentManager(),"SUBMIT_DIALOG");
    }

    protected String getText(EditText editText){
        return editText.getText().toString().trim();
    }

    protected boolean actionControl(String tag)
    {
        if(Constant.AUTHORITY_LIST.contains(tag)) {
            return false;
        }else{
            FreeApi_DialogUtils.getConfirmDialog(this, "确定","无权限", () -> {

            }).show(getSupportFragmentManager(),"AUTH_DIALOG");
            return true;
        }
    }

    protected boolean actionControl1(String tag)
    {
        if(Constant.AUTHORITY_LIST.contains(tag)) {
            return false;
        }else{
            FreeApi_DialogUtils.getConfirmDialog(this, "确定","无权限，请联系领班处理！", () -> {

            }).show(getSupportFragmentManager(),"AUTH_DIALOG");
            return true;
        }
    }

    protected boolean actionControls(String tag)
    {
        if(Constant.AUTHORITY_LIST.contains(tag)) {
            return false;
        }else{
            return true;
        }
    }
}
